import datetime
import logging
from django.db import transaction

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from finance.api.utils import update_account
from finance.models import FundBill

logger = logging.getLogger("django")


class MobileFundBillSerializer(ModelSerializer):
    """资金账单"""
    employee_name = serializers.CharField(source='employee.name', read_only=True)
    account_name = serializers.CharField(source='account.name', read_only=True)
    title_name = serializers.CharField(source='acc_title.name', read_only=True)
    user_name = serializers.CharField(source='user.real_name', read_only=True)
    verify_name = serializers.CharField(source='get_verify_display', read_only=True)
    over_flag = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = FundBill
        exclude = ['update_at', 'create_at']

    def get_over_flag(self, obj):
        order_time = obj.order_time or datetime.datetime.now().date()
        return (datetime.datetime.now().date() - order_time).days

    def create(self, validated_data):
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            instance = None
            try:
                instance = self.Meta.model.objects.create(**validated_data)
                if instance.verify == 1:
                    self.update_account(instance)
            except Exception as e:
                logging.info("Create: {}".format(e))
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)
        return instance

    def update(self, instance, validated_data):
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                instance.order_no = validated_data.get('order_no', instance.order_no)
                instance.employee = validated_data.get('employee', instance.employee)
                instance.acc_title = validated_data.get('acc_title', instance.acc_title)
                instance.account = validated_data.get('account', instance.account)

                instance.money = validated_data.get('money', instance.money)
                instance.order_time = validated_data.get('order_time', instance.order_time)
                instance.category = validated_data.get('category', instance.category)

                instance.desc = validated_data.get('desc', instance.desc)
                instance.source = validated_data.get('source', instance.source)
                instance.user = validated_data.get('user', instance.user)
                old_verify = instance.verify
                instance.verify = validated_data.get('verify', instance.verify)

                instance.save()
                if (old_verify == 0 or old_verify is None) and instance.verify == 1:
                    self.update_account(instance)
            except Exception as e:
                logging.info("update: {}".format(e))
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)

        return instance

    def update_account(self, obj):
        if obj.category == 0:
            update_account(obj.account_id, obj.money)



